import React, { Component } from 'react'
import { Card, Input, List, message } from "antd";
import ArticleInfo from '../../types/ArticleInfo';
import './articleList.less'
import { listArticleInfoReq, queryArticleAmount, queryArticlePicturePath, searchArticleInfo } from "../../requests/article"
import moment from 'moment';
import { Link } from 'react-router-dom';
import ArticleType from "../../types/ArticleType";
import { getRes } from "../../configFile";
import defaultPic from '../../static/images/default.png';
import Axios from 'axios';

//props接口
interface IProps {
    title: React.ReactNode
    articleType: ArticleType
}
interface IState {
    articleSource: Array<Pick<ArticleInfo, "articleID" | "articleType" | "title" | "authorID" | "creationTimestamp" | "lastModifiedTimestamp">>
    coverSource: Map<number, string>
    amount: number
    offset: number
    limit: number
    isSearch: boolean
}

const { Search } = Input;

export default class ArticleList extends Component<IProps, IState> {
    constructor(props: IProps) {
        super(props)
        this.state = {
            articleSource: [],
            coverSource: new Map(),
            amount: 0,
            offset: 0,
            limit: 10,
            isSearch: false
        }
    }
    //获取文章数据
    getArticles = async () => {
        try {
            const amountRes = getRes(await queryArticleAmount(this.props.articleType))
            const res = getRes(await listArticleInfoReq(this.props.articleType, this.state.offset, this.state.limit))
            if (amountRes.isSuccessful && res.isSuccessful) {
                this.setState({
                    articleSource: res.data,
                    amount: amountRes.data
                })
            } else {
                message.error("获取失败")
            }
            this.getCovers();

        }
        catch (error) {
            message.error(error.toString())
        }
    }

    //获取文章封面
    getCovers = async () => {
        try {
            const coversRes = await Axios.all(this.state.articleSource.map(article => queryArticlePicturePath(article.articleID)));
            this.state.articleSource.forEach((article, index) => {  //使用forEach不需要返回值
                this.state.coverSource.set(article.articleID, getRes(coversRes[index]).data)
            })
            this.setState({ ...this.state })    //更新state
        } catch (err) { }
    }

    paginationChange = async (page: number, pageSize: number | undefined) => {
        if (!!pageSize) {
            this.setState({
                offset: (page - 1) * (pageSize),
                limit: (pageSize)
            }, () => {
                this.getArticles()
            })

        } else {
            console.error('pageSize === undefined')
        }
    }
    async componentDidMount() {
        await this.getArticles()
    }

    onSearch: (values: string) => void = async values => {
        if (values === '') {
            await this.getArticles()
        } else {
            try {
                const res = getRes(await searchArticleInfo(values, this.props.articleType))
                if (!res.isSuccessful) {
                    console.error(res);
                    message.error("查询失败" + res.message)
                }
                this.setState({ articleSource: res.data, amount: res.data.length, isSearch: true })
                this.getCovers();
            } catch (err) {
                message.error(JSON.stringify(err))
            }
        }
    }

    render() {
        return (
            <Card
                title={<>{this.props.title}</>}
                bordered={false}
                headStyle={{ fontSize: '20px' }}
            >
                <Search placeholder="搜索" onSearch={values => this.onSearch(values)} allowClear={true} enterButton />
                <List
                    style={{ minHeight: '1200px' }}
                    size="large"
                    pagination={{
                        defaultPageSize: this.state.limit,
                        total: this.state.amount,
                        showSizeChanger: false,
                        onChange: this.state.isSearch ? undefined : this.paginationChange,
                    }}
                    dataSource={this.state.articleSource}
                    renderItem={
                        item => {
                            return (
                                <div key={item.title} className="articleListItem">
                                    <div className="imgBox">
                                        <img
                                            alt="logo"
                                            src={this.state.coverSource.get(item.articleID)
                                                ?
                                                this.state.coverSource.get(item.articleID)
                                                :
                                                defaultPic}
                                            style={{ height: '100%' }}
                                        />
                                    </div>
                                    <div className="articleListItemTextBox">
                                        <div className='titleLine'>
                                            <div className='titleLink'><Link to={`/article/${item.articleID}`}>{item.title}</Link></div>
                                        </div>
                                        <div className="extra"><div className="author"> 作者：{item.authorID}</div> <div className="timestamp">{moment(item.creationTimestamp).format('YYYY-MM-DD')}</div></div>
                                    </div>
                                </div>
                            )
                        }}
                />
            </Card>
        )
    }
}
